import { Pipe, PipeTransform } from '@angular/core';
import { Http }                from '@angular/http';

import 'rxjs/add/operator/map';

@Pipe({
  name: 'fetch',
  pure: false
})
export class FetchJsonPipe  implements PipeTransform {

  // 这个管道只有当所请求的URL发生变化时才会向服务器发起请求。它会缓存服务器的响应。
  // pure: false  代表非纯管道
  // 纯管道： 当对象的引用发生了变化才会调用纯管道
  // 非纯管道： 进行递归的深检查，发生变化调用非纯管道

  private cachedData: any = null;
  private cachedUrl = '';

  constructor(private http: Http) { }

  transform(url: string): any {
    if (url !== this.cachedUrl) {
      this.cachedData = null;
      this.cachedUrl = url;
      this.http
        .get(url)
        .map( result => result.json() )
        .subscribe( result => this.cachedData = result );
    }
    return this.cachedData;
  }
}
